import datetime

from PyQt4 import QtGui, QtCore

from preview_widget import Preview
from bot import Bot
import language

class CalTable(QtGui.QDialog):

    def __init__(self, parent, tdb, date=datetime.date.today(), byMonth=True, serie=''):
        QtGui.QWidget.__init__(self, parent)
        self._db = tdb
        self._notif = parent.notif
        self._date = date
        self._byMonth = byMonth
        self.lang = language.setup()
        if self._byMonth:
            self._calendars = self._obtain_calendar(0)
            self._table = QtGui.QTableWidget(1, 4)
            self._table.setHorizontalHeaderLabels(self.lang['tableHeader'])
            self.setFixedWidth(800)
        else:
            self.setWindowTitle(serie.upper() + ' ' + self.lang['calendar'])
            self._calendars = self._obtain_calendar_serie(serie)
            self._table = QtGui.QTableWidget(1, 5)
            self._table.setHorizontalHeaderLabels(self.lang['tableHeader']+self.lang['date'])
            self.setFixedWidth(900)
        v_box = QtGui.QVBoxLayout(self)
        h_box = QtGui.QHBoxLayout()
        self._table.setSelectionBehavior(QtGui.QAbstractItemView.SelectRows)
        self._table.removeRow(0)
        self._table.setToolTip(self.lang['press'])
        self._table.setColumnWidth(0, 200)
        self._table.setColumnWidth(3, 350)
        self._table.horizontalHeader().setStretchLastSection(True)
        self._table.setSortingEnabled(True)
        h_box.addWidget(self._table)
        self._set_data()
        h_box2 = QtGui.QHBoxLayout()
        self._overview = QtGui.QPushButton(self.lang['overview'])
        self._episodes = QtGui.QPushButton(self.lang['epiList'])
        h_box2.addWidget(self._overview)
        h_box2.addWidget(self._episodes)
        v_box.addWidget(QtGui.QLabel(self.lang['press']))
        v_box.addLayout(h_box)
        v_box.addLayout(h_box2)
        self._shortRight = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Right), self._table)
        self._shortLeft = QtGui.QShortcut(QtGui.QKeySequence(QtCore.Qt.Key_Left), self._table)

        self.connect(self._overview, QtCore.SIGNAL("clicked()"), self._open_imdb)
        self.connect(self._episodes, QtCore.SIGNAL("clicked()"), self._open_episodes)
        self.connect(self._shortLeft, QtCore.SIGNAL("activated()"), lambda: self._reload_table(-1))
        self.connect(self._shortRight, QtCore.SIGNAL("activated()"), lambda: self._reload_table(+1))

    def _reload_table(self, day):
        if self._byMonth:
            while self._table.rowCount() > 0:
                self._table.removeRow(0)
            self._calendars = self._obtain_calendar(day)
            self._set_data()

    def _obtain_calendar(self, day):
        dif = datetime.timedelta(days=day)
        self._date = self._date + dif
        self.setWindowTitle('Series: ' + self._date.strftime("%A %d. %B %Y"))
        calendars = self._db.restore_calendar_for_date(self._date)
        return calendars
        
    def _obtain_calendar_serie(self, serie):
        calendars = self._db.restore_calendar(serie)
        return calendars

    def _set_data(self):
        r = 0
        icon = self._db.read_configuration()[5]
        for cal in self._calendars:
            self._table.insertRow(r)
            item = QtGui.QTableWidgetItem(str(cal.season))
            item.setFlags( QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
            self._table.setItem(r, 1, item)
            item = QtGui.QTableWidgetItem(str(cal.nroEp))
            item.setFlags( QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
            self._table.setItem(r, 2, item)
            item = QtGui.QTableWidgetItem(str(cal.episode))
            item.setFlags( QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
            self._table.setItem(r, 3, item)
            if not self._byMonth:
                item = QtGui.QTableWidgetItem(str(cal.date))
                item.setFlags( QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
                self._table.setItem(r, 4, item)
            if icon == 1:
                imageFile = self._db.dire + cal.serie.replace(' ', '+')
                item = QtGui.QTableWidgetItem(QtGui.QIcon(imageFile), str(cal.serie).upper())
            else:
                item = QtGui.QTableWidgetItem(str(cal.serie).upper())
            item.setFlags( QtCore.Qt.ItemIsSelectable |  QtCore.Qt.ItemIsEnabled )
            self._table.setItem(r, 0, item)
            r += 1

    def _open_imdb(self):
        pos = self._table.currentRow()
        if pos > -1:
            self._notif.show_message('LOADING...', self.lang['overview'])
            serie = str(self._table.item(pos, 0).text())
            prev = Preview(self, serie, 0)
            prev.show()

    def _open_episodes(self):
        pos = self._table.currentRow()
        if pos > -1:
            self._notif.show_message('LOADING...', self.lang['epiList'])
            serie = str(self._table.item(pos, 0).text())
            season = int(self._table.item(pos, 1).text())
            prev = Preview(self, serie, season)
            prev.show()

    def closeEvent(self, event):
        event.ignore()
        self.done(0)
